<?php
require_once '../../config/database.php';
require_once '../../utils/Database.php';
require_once '../../utils/WeChatAuth.php';
require_once '../../utils/Response.php';

$db = new Database();
$auth = new WeChatAuth();

// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 检查管理员权限
function checkAdminPermission($requiredPermission = null) {
    global $auth, $db;
    $user = $auth->getCurrentUser();
    if (!$user) {
        Response::authError('请先登录');
    }
    
    // 检查是否为管理员
    $adminUser = $db->fetchOne("
        SELECT au.*, ar.permissions, ar.role_code 
        FROM admin_users au 
        JOIN admin_roles ar ON au.role_id = ar.id 
        WHERE au.user_id = ? AND au.is_active = 1 AND ar.is_active = 1
    ", [$user['id']]);
    
    if (!$adminUser) {
        Response::error('权限不足');
    }
    
    // 检查具体权限
    if ($requiredPermission) {
        $permissions = json_decode($adminUser['permissions'], true);
        if (!in_array('*', $permissions) && !in_array($requiredPermission, $permissions)) {
            // 检查模块权限（如 team.*）
            $modulePermission = explode('.', $requiredPermission)[0] . '.*';
            if (!in_array($modulePermission, $permissions)) {
                Response::error('权限不足');
            }
        }
    }
    
    return $adminUser;
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        $admin = checkAdminPermission('team.view');
        
        switch ($action) {
            case 'list':
                // 获取团队预约申请列表
                $page = (int)($_GET['page'] ?? 1);
                $limit = (int)($_GET['limit'] ?? 20);
                $search = $_GET['search'] ?? '';
                $status = $_GET['status'] ?? '';
                $teamType = $_GET['team_type'] ?? '';
                $dateFrom = $_GET['date_from'] ?? '';
                $dateTo = $_GET['date_to'] ?? '';
                $offset = ($page - 1) * $limit;
                
                $whereConditions = [];
                $params = [];
                
                if ($search) {
                    $whereConditions[] = "(tr.team_name LIKE ? OR tr.leader_name LIKE ? OR tr.leader_phone LIKE ? OR tr.organization LIKE ? OR u.nickname LIKE ?)";
                    $searchTerm = "%{$search}%";
                    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm]);
                }
                
                if ($status) {
                    $whereConditions[] = "tr.status = ?";
                    $params[] = $status;
                }
                
                if ($teamType) {
                    $whereConditions[] = "tr.team_type = ?";
                    $params[] = $teamType;
                }
                
                if ($dateFrom) {
                    $whereConditions[] = "tr.visit_date >= ?";
                    $params[] = $dateFrom;
                }
                
                if ($dateTo) {
                    $whereConditions[] = "tr.visit_date <= ?";
                    $params[] = $dateTo;
                }
                
                $whereClause = '';
                if (!empty($whereConditions)) {
                    $whereClause = 'WHERE ' . implode(' AND ', $whereConditions);
                }
                
                // 获取团队预约申请列表
                $teams = $db->fetchAll("
                    SELECT tr.*, u.nickname, u.phone as user_phone, u.avatar_url
                    FROM team_reservations tr
                    LEFT JOIN users u ON tr.user_id = u.id
                    {$whereClause}
                    ORDER BY tr.created_at DESC
                    LIMIT ? OFFSET ?
                ", array_merge($params, [$limit, $offset]));
                
                // 获取总数
                $total = $db->fetchOne("
                    SELECT COUNT(*) as count 
                    FROM team_reservations tr
                    LEFT JOIN users u ON tr.user_id = u.id
                    {$whereClause}
                ", $params)['count'];
                
                Response::success([
                    'teams' => $teams,
                    'pagination' => [
                        'current_page' => $page,
                        'per_page' => $limit,
                        'total' => (int)$total,
                        'total_pages' => ceil($total / $limit)
                    ]
                ], '获取成功');
                break;
                
            case 'detail':
                // 获取团队预约申请详情
                $teamId = (int)($_GET['id'] ?? 0);
                if (!$teamId) {
                    Response::error('缺少团队预约ID');
                }
                
                $team = $db->fetchOne("
                    SELECT tr.*, u.nickname, u.phone as user_phone, u.avatar_url, u.openid
                    FROM team_reservations tr
                    LEFT JOIN users u ON tr.user_id = u.id
                    WHERE tr.id = ?
                ", [$teamId]);
                
                if (!$team) {
                    Response::error('团队预约申请不存在');
                }
                
                Response::success($team, '获取成功');
                break;
                
            case 'statistics':
                // 获取团队预约统计
                $dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
                $dateTo = $_GET['date_to'] ?? date('Y-m-d');
                
                // 总体统计
                $totalStats = $db->fetchOne("
                    SELECT 
                        COUNT(*) as total_applications,
                        COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
                        COUNT(CASE WHEN status = 'approved' THEN 1 END) as approved_count,
                        COUNT(CASE WHEN status = 'rejected' THEN 1 END) as rejected_count,
                        COUNT(CASE WHEN status = 'confirmed' THEN 1 END) as confirmed_count,
                        COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_count,
                        COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled_count,
                        SUM(participant_count) as total_participants,
                        COUNT(CASE WHEN guide_needed = 1 THEN 1 END) as guide_needed_count
                    FROM team_reservations 
                    WHERE visit_date BETWEEN ? AND ?
                ", [$dateFrom, $dateTo]);
                
                // 按类型统计
                $typeStats = $db->fetchAll("
                    SELECT 
                        team_type,
                        COUNT(*) as application_count,
                        SUM(participant_count) as participant_count
                    FROM team_reservations 
                    WHERE visit_date BETWEEN ? AND ?
                    AND team_type IS NOT NULL AND team_type != ''
                    GROUP BY team_type
                    ORDER BY application_count DESC
                ", [$dateFrom, $dateTo]);
                
                // 按机构统计
                $organizationStats = $db->fetchAll("
                    SELECT 
                        organization,
                        COUNT(*) as application_count,
                        SUM(participant_count) as participant_count
                    FROM team_reservations 
                    WHERE visit_date BETWEEN ? AND ?
                    AND organization IS NOT NULL AND organization != ''
                    GROUP BY organization
                    ORDER BY application_count DESC
                    LIMIT 10
                ", [$dateFrom, $dateTo]);
                
                // 按月统计
                $monthlyStats = $db->fetchAll("
                    SELECT 
                        DATE_FORMAT(visit_date, '%Y-%m') as month,
                        COUNT(*) as application_count,
                        SUM(participant_count) as participant_count
                    FROM team_reservations 
                    WHERE visit_date BETWEEN ? AND ?
                    GROUP BY DATE_FORMAT(visit_date, '%Y-%m')
                    ORDER BY month
                ", [$dateFrom, $dateTo]);
                
                Response::success([
                    'total_stats' => $totalStats,
                    'type_stats' => $typeStats,
                    'organization_stats' => $organizationStats,
                    'monthly_stats' => $monthlyStats,
                    'period' => ['from' => $dateFrom, 'to' => $dateTo]
                ], '获取成功');
                break;
                
            case 'types':
                // 获取团队类型列表
                $types = $db->fetchAll("
                    SELECT DISTINCT team_type, COUNT(*) as count
                    FROM team_reservations 
                    WHERE team_type IS NOT NULL AND team_type != ''
                    GROUP BY team_type
                    ORDER BY count DESC
                ");
                
                Response::success($types, '获取成功');
                break;
                
            case 'guides':
                // 获取可用讲解员列表
                $guides = $db->fetchAll("
                    SELECT id, name, phone, languages, available_days
                    FROM volunteer_applications 
                    WHERE status = 'active'
                    ORDER BY name
                ");
                
                Response::success($guides, '获取成功');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'PUT':
        $admin = checkAdminPermission('team.update');
        
        switch ($action) {
            case 'update_status':
                // 更新团队预约申请状态
                if (!isset($input['team_id']) || !isset($input['status'])) {
                    Response::error('缺少必要参数');
                }
                
                $teamId = (int)$input['team_id'];
                $status = $input['status'];
                $adminNotes = $input['admin_notes'] ?? '';
                $approvedTimeSlot = $input['approved_time_slot'] ?? '';
                $assignedGuide = $input['assigned_guide'] ?? '';
                
                // 验证状态值
                $validStatuses = ['pending', 'approved', 'rejected', 'confirmed', 'completed', 'cancelled'];
                if (!in_array($status, $validStatuses)) {
                    Response::error('无效的状态值');
                }
                
                $updateData = [
                    'status' => $status,
                    'admin_notes' => $adminNotes,
                    'updated_at' => date('Y-m-d H:i:s')
                ];
                
                if ($approvedTimeSlot) {
                    $updateData['approved_time_slot'] = $approvedTimeSlot;
                }
                
                if ($assignedGuide) {
                    $updateData['assigned_guide'] = $assignedGuide;
                }
                
                // 如果状态改为confirmed，生成预约码
                if ($status === 'confirmed' && !$input['reservation_code']) {
                    $updateData['reservation_code'] = generateReservationCode();
                }
                
                $result = $db->update('team_reservations', $updateData, 'id = ?', [$teamId]);
                
                if ($result) {
                    Response::success([
                        'team_id' => $teamId,
                        'reservation_code' => $updateData['reservation_code'] ?? null
                    ], '更新成功');
                } else {
                    Response::error('更新失败');
                }
                break;
                
            case 'batch_update':
                // 批量更新状态
                if (!isset($input['team_ids']) || !isset($input['status'])) {
                    Response::error('缺少必要参数');
                }
                
                $teamIds = $input['team_ids'];
                $status = $input['status'];
                $adminNotes = $input['admin_notes'] ?? '';
                
                if (!is_array($teamIds) || empty($teamIds)) {
                    Response::error('团队预约ID列表格式错误');
                }
                
                // 验证状态值
                $validStatuses = ['pending', 'approved', 'rejected', 'confirmed', 'completed', 'cancelled'];
                if (!in_array($status, $validStatuses)) {
                    Response::error('无效的状态值');
                }
                
                $placeholders = str_repeat('?,', count($teamIds) - 1) . '?';
                $params = array_merge($teamIds, [$status, $adminNotes, date('Y-m-d H:i:s')]);
                
                $result = $db->query("
                    UPDATE team_reservations 
                    SET status = ?, admin_notes = ?, updated_at = ?
                    WHERE id IN ({$placeholders})
                ", $params);
                
                if ($result) {
                    Response::success(['count' => count($teamIds)], '批量更新成功');
                } else {
                    Response::error('批量更新失败');
                }
                break;
                
            case 'assign_guide':
                // 分配讲解员
                if (!isset($input['team_id']) || !isset($input['guide_name'])) {
                    Response::error('缺少必要参数');
                }
                
                $teamId = (int)$input['team_id'];
                $guideName = $input['guide_name'];
                $adminNotes = $input['admin_notes'] ?? '';
                
                $result = $db->update('team_reservations', [
                    'assigned_guide' => $guideName,
                    'admin_notes' => $adminNotes,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = ?', [$teamId]);
                
                if ($result) {
                    Response::success(['team_id' => $teamId], '分配讲解员成功');
                } else {
                    Response::error('分配讲解员失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'DELETE':
        $admin = checkAdminPermission('team.delete');
        
        switch ($action) {
            case 'delete':
                // 删除团队预约申请
                $teamId = (int)($_GET['id'] ?? 0);
                if (!$teamId) {
                    Response::error('缺少团队预约ID');
                }
                
                $result = $db->delete('team_reservations', 'id = ?', [$teamId]);
                
                if ($result) {
                    Response::success(['team_id' => $teamId], '删除成功');
                } else {
                    Response::error('删除失败');
                }
                break;
                
            case 'batch_delete':
                // 批量删除
                if (!isset($_GET['ids'])) {
                    Response::error('缺少团队预约ID列表');
                }
                
                $teamIds = explode(',', $_GET['ids']);
                $teamIds = array_map('intval', $teamIds);
                $teamIds = array_filter($teamIds);
                
                if (empty($teamIds)) {
                    Response::error('团队预约ID列表为空');
                }
                
                $placeholders = str_repeat('?,', count($teamIds) - 1) . '?';
                $result = $db->query("DELETE FROM team_reservations WHERE id IN ({$placeholders})", $teamIds);
                
                if ($result) {
                    Response::success(['count' => count($teamIds)], '批量删除成功');
                } else {
                    Response::error('批量删除失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}

// 生成预约码
function generateReservationCode() {
    return 'TEAM' . strtoupper(substr(md5(uniqid() . time()), 0, 8));
}
?>